import SessionUtil, { JxbHttpClient, Session }  from '../data/session/session';
import SessionSellingServerUtil from '../data/session/sessionSellingServer';
import SessionUserUtil from '../data/session/sessionUser';
import SellingServerUtil from "../data/sellingServer"
import { JxbResponseError } from './network';
import SystemUtil from '../shell/system/system';
import PageUtil from '../shell/router/page';

// 获取屏幕宽度
function w_widths(page) {
    page.setData({
        w_width: SystemUtil.getSystemInfo(false).windowWidth,
    })
}

function changeConsulant(vCardId) {
    SessionUtil.getInstance().then(session => {
        let activeServer = session.getTheSellingServerSync(),sessionUser = session.getTheSessionUserSync()
        if(sessionUser.isSalesman){
            return [activeServer, activeServer]
        }
        if(activeServer.getTheVCardSync().id === vCardId){
            console.log('同一个顾问')
            return [activeServer, activeServer]
        }
        return Promise.all([SellingServerUtil.getInstance(vCardId), activeServer])
    }).then(servers => {
        console.log('servers common js', servers)
        let [promoteServer, activeServer] = servers,
            lastAccessedServer = activeServer.getTheLastAccessedServerSync()
        console.log('promoteServer', promoteServer.salesmanId, promoteServer)
        console.log('activeServer', activeServer.salesmanId, activeServer)
        if(lastAccessedServer){
            console.log('lastAccessedServer', lastAccessedServer.salesmanId, lastAccessedServer)
        }
        let curPage = PageUtil.getHistory(-1),
            accessUri = PageUtil.getUri(curPage);
        accessUri = encodeURIComponent(accessUri);
        console.log('referer', curPage, accessUri);
        if(activeServer.isConfirmed){
            // 当前顾问不是临时顾问
            if(promoteServer.salesmanId === activeServer.salesmanId){
                // 来源顾问和当前顾问为同一个人
                // 静默处理
                return
            }else{
                // 来源顾问不是当前顾问
                // 展示是否切换顾问的提示
                console.log('jump to switch sellingServer',`/pages/consulant/consulant?promoterId=${promoteServer.salesmanId}&salesmanId=${activeServer.salesmanId}&tipType=with_selection&_r=${accessUri}`)
                wx.navigateTo({
                    url: `/pages/consulant/consulant?promoterId=${promoteServer.salesmanId}&salesmanId=${activeServer.salesmanId}&tipType=with_selection&_r=${accessUri}`,
                })
            }
        }else {
            // 当前顾问是临时顾问
            if(lastAccessedServer && lastAccessedServer.isConfirmed === true && lastAccessedServer.isServiceable === true){
                // 上次访问的顾问不是临时顾问且可以提供服务
                // 展示是否切换顾问的提示
                wx.navigateTo({
                    url: `/pages/consulant/consulant?promoterId=${promoteServer.salesmanId}&salesmanId=${lastAccessedServer.salesmanId}&tipType=with_selection&_r=${accessUri}`,
                })
            }else{
                // 之前的顾问是临顾问或该顾问无法提供服务了
                // 展示来源顾问，并让客户确认（只能找该顾问买酒）
                wx.navigateTo({
                    url: `/pages/consulant/consulant?promoterId=${promoteServer.salesmanId}&tipType=no_selection&_r=${accessUri}`,
                })
            }
        }
    })
}

/**
 * 通过consultant_id或salesman_id获取顾问全部信息
 * 
 * @todo 仅被 pages/signup/index/index.js 引用
 */
function getConlantInfo(id, isConsultantId = true, callback) {
    if(id >= 0 || typeof id === 'object'){
        var requestData;
        if(typeof id === 'object'){
            requestData = id
        }else if (isConsultantId) {
            requestData = {
                consultant_id: id,
            };
        } else {
            requestData = {
                salesman_id: id,
            };
        }
        (new JxbHttpClient()).request({
            url: 'AppMaster/AppletRegister/getConsultantsInfo',
            data: requestData,
            header: {
                'content-type': 'json'
            },
        }).then(jxbResp => {
            if (jxbResp.data.result == 0) {
                if (callback) {
                    callback(jxbResp.data);
                }
            }
        })
    } else if (callback) {
        callback();
    }
}


/**
 * 通过consultant_id或salesman_id或sn获取顾问全部信息
 * 
 * @todo 仅被 pages/transition/index/index.js 引用
 */
function getConlantInfoSn(id, isConsultantId = true, callback, sn) {
    if (sn) {
        requestData = {
            consultant_sn: id,
        };
    }  else if (id >= 0) {
        var requestData;
        if (isConsultantId) {
            requestData = {
                consultant_id: id,
            };
        } else {
            requestData = {
                salesman_id: id,
            };
        }
    }
    (new JxbHttpClient()).request({
        url: 'AppMaster/AppletRegister/getConsultantsInfo',
        data: requestData,
        header: {
            'content-type': 'json'
        },
    }).then(jxbResp => {
        if (typeof callback === 'function') {
            callback(jxbResp.data);
        }
    });
}

/**
 * @description 获取用户当前顾问信息
 * @method showContips
 * @param page 调用此方法页面的this
 * @returns {Promise<string>}
 *
 */
function showContips(page) {
    return SessionUtil.getInstance().then(session => {
        return session.getTheSellingServer()
    }).then( server =>{
        wx.setStorageSync("shop_name", server.showName);
        wx.setStorageSync("store", server.showName);
        let vCard = server.getTheVCardSync(),
            isShowVCardBar = false,
            vCardInfo = {
                name: vCard.name,
                head_img: vCard.avatarUri,
                isshow_detail: false,
                mobile: vCard.contactPhone,
                contact_phone: vCard.contactPhone
            }
        if(vCard.id) isShowVCardBar = true
        page.setData({
            isShowConsulantBar: isShowVCardBar,
            current_consultant_info: vCardInfo
        })
        return server.showName
    }).catch(error => {
        page.setData({
            current_consultant_info: {}
        })
        console.log(error.message, error)
        throw error;
    })
}

/**
 * @description 判断是否展示页面左下角顾问详情条
 * @method show_bar
 * @param flag 判断条件
 * @param page 调用此方法页面的this
 * @returns void
 *
 */
function show_bar(flag = true, page) {
    var info = page.data.current_consultant_info;
    if (flag) {
        info.isshow_detail = !info.isshow_detail;
    } else {
        info.isshow_detail = false;
    }

    page.setData({
        current_consultant_info: info
    })
}

/**
 * 判断是否为批发商，是->列表，否->首页
 * 
 * @todo 待废除，仅被 pages/login/login.js 引用
 */
function wholesale(){
    SessionUtil.getInstance().then(session => {
        return session.getTheSellingServer()
    }).then(server => {
        let agent = server.getTheAgentSync()
        if(agent.isWholesale){
            setTimeout(function () {
                wx.switchTab({
                    url: '/pages/product/index/index',
                })
            }, 2000)
        }else{
            console.log('is retail')
            setTimeout(function () {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }, 2000)
        }
    })
}

/**
 * 发起会话请求
 * 
 * @param {object} config 
 * @param {number} tryTimes 
 */
function my_request(config, tryTimes) {
    let client = new JxbHttpClient();
    client.setFailTryCount(tryTimes)
    .request(config)
    .then(jxbResp=>{
        if (typeof config.success === 'function') {
            config.success(jxbResp);
        }
    })
    .catch(err=>{
        if(err instanceof JxbResponseError){
            if(typeof config.fail === 'function'){
                config.fail(err.httpResponse)
            }
        }
    });
    return
}

// 判断登录
function if_login() {

    if (get_token()) {
        console.log('is login!');
    } else {
        console.log('not login!');
        wx.showToast({
            title: '登录异常',
            icon: 'loading',
            duration: 2000
        })
        wx.redirectTo({
            // url: '/pages/login/login'
            url:'/pages/my/logintype/logintype'
        })
    }
}

// 判断登录 2
function if_login2(MSG) {
    if (MSG == '请登录') {
        console.log('not login!');
        wx.showToast({
            title: '登录异常',
            icon: 'loading',
            duration: 2000
        })
        wx.redirectTo({
            // url: '/pages/login/login'
            url:'/pages/my/logintype/logintype'
        })
    }
}

/**
 * 获取TOKEN
 * 
 * @todo 待废除
 */
function get_token() {
    let session = SessionUtil.getInstanceSync()
    if(session instanceof Session){
        
        return session.token;
    }
    return '';
}

/**
 * 用户信息变更
 * 
 * @param {function} callback
 * @param {sessionUser} callback.user
 * @todo 待废除
 */
function when_user_change_clear_the_storage(callback){
    wx.removeStorageSync('customer');
    wx.removeStorageSync('logs');
    wx.removeStorageSync('tagValue');
    wx.removeStorageSync('phone');
    wx.removeStorageSync('Filter');
    wx.removeStorageSync('agent');
    wx.removeStorageSync('user_id');
    wx.removeStorageSync('user_type');
    wx.removeStorageSync('consultantId');
    wx.removeStorageSync("shop_name");
    wx.removeStorageSync("addressId");
    wx.removeStorageSync('waddress');
    Promise.all([SessionSellingServerUtil.renewCache(), SessionUserUtil.renewCache()])
    .then(resp => {
        // let [server, user] = resp
        if (typeof callback === 'function') callback();
    })
}


// 确认提示框
function Alert(Title, Message, callback) {
    wx.showModal({
        title: Title,
        content: Message,
        showCancel: false,
        success: function (res) {
            if(callback) callback();
        }
    })
}

// 从数组中删除指定值元素
function removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}

// 判断元素是否在数组内
function contains(arr, obj) {
    var i = arr.length;
    while (i--) {
        if (arr[i] === obj) {
            return true;
        }
    }
    return false;
}

/**
 * 页面跳转处理器
 */
function PageJump(route, data) {
    var pages = getCurrentPages();
    var a = 0;
    for (var i = 0; i < pages.length; i++) {
        if (pages[i].route == route) {
            a = 1;
            var prevPage = pages[i];
            prevPage.setData(data);
            wx.navigateBack({
                delta: (pages.length - i - 1)
            })
        }
    }
    if (a == 0) {
        wx.navigateTo({
            url: '/' + route,
        })
    }
}

//自适应获取高度--单个
function imageLoad(e, w) {
    var page = this;
    var $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = w,           //设置图片显示宽度，左右留有16rpx边距
        viewHeight = w / ratio;    //计算的高度值
    var imageHeight = page.data.imageSize;
    imageHeight.push(viewHeight);
    return imageHeight;
}

//自适应获取高度--第二种
function imageLoadAn(e, w) {
    var page = this;
    var $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = w,           //设置图片显示宽度，左右留有20rpx边距
        viewHeight = viewWidth / ratio;    //计算的高度值
    return viewHeight;
}


/**自适应获取高度--多个 */
function imageLoadList(e, page) {
    w_widths(page);
    var index = e.currentTarget.dataset.id;;
    var $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = page.data.w_width,           //设置图片显示宽度，左右留有20rpx边距
        viewHeight = viewWidth / ratio;    //计算的高度值
    var imageHeight = page.data.imageSize;
    imageHeight[index] = viewHeight.toFixed(2);
    page.setData({
        imageSize: imageHeight
    })
}

/**弹窗 */
function showToast(msg, status){
    var icon;
    if (status){
        wx.showToast({
            title: msg,
            icon: 'success',
            duration: 2000
        })
    } else {
        wx.showToast({
            title: msg,
            image: '/pages/imges/fail.png',
            duration: 2000
        })
    }
}
function weixinPay(orderno, paymoney, callback) {
    wx.login({
        success: function (loginres) {
            if (loginres.code) {
                // 请求下单支付
               my_request({
                    url: '/AppMaster/PosOrder/payWeChat',
                    data: {
                        orderno: orderno,
                        code: loginres.code
                    },
                    success: function (res) {
                        if (res.data.result == 0) {
                            var mobile = res.data.data.salesman_mobile
                            var name = res.data.data.salesman_name
                            if (mobile) {
                                var content;
                                content = '订单已提交！'+'请直接用支付宝或微信等方式向 ' + name + ' 支付 ' + paymoney + ' 元即可完成订单。'
                                wx.showModal({
                                    content: content,
                                    confirmText: '联系顾问',
                                    confirmColor: '#3bc528',
                                    cancelText: '确定',
                                    cancelColor: '#888',
                                    success: function (res) {
                                        if (res.confirm) {
                                            wx.makePhoneCall({
                                                phoneNumber: mobile,
                                                complete: function (res) {
                                                    console.log(res)
                                                    if (callback) callback();
                                                }
                                            })
                                        } else if (res.cancel) {
                                            if (callback) callback();
                                        }
                                    }
                                })
                                return false;
                            }
                            var timeStamp = res.data.data.timeStamp + "";
                            var nonceStr = res.data.data.nonceStr;
                            var pack = res.data.data.package;
                            var signType = res.data.data.signType;
                            var paySign = res.data.data.paySign;

                            // 调用wx.requestPayment(OBJECT)发起微信支付
                            wx.requestPayment({
                                'timeStamp': timeStamp,
                                'nonceStr': nonceStr,
                                'package': pack,
                                'signType': signType,
                                'paySign': paySign,
                                'success': function (res) {
                                    wx.showToast({
                                        title: '订单支付成功!',
                                        image: '/pages/images/succ.png',
                                        duration: 2000
                                    })
                                    setTimeout(function () {
                                        if (callback) callback(true);
                                    }, 1000)
                                },
                                'fail': function (res) {
                                    // console.log("失败");
                                    wx.showToast({
                                        title: '订单支付失败!',
                                        image: '/pages/images/fail.png',
                                        duration: 2000
                                    })
                                    setTimeout(function () {
                                        if (callback) callback(false);
                                    }, 1000)
                                },
                                'complete': function (res) {
                                    // console.log("完成");
                                    // console.log(res);
                                }
                            });
                        } else {
                            console.log(res.data.message);
                            if_login2(res.data.message);
                        }
                    }
                });
            } else {
                console.log('获取用户登录态失败！' + loginres.errMsg)
                wx.switchTab({
                    url: '/pages/order/index/index'
                })
            }
        },
        fail:function(){
            wx.switchTab({
                url: '/pages/order/index/index'
            })
        },
    })
}
module.exports = {
    get_token: get_token,
    if_login: if_login,
    if_login2: if_login2,
    showToast:showToast,
    Alert: Alert,
    contains: contains,
    removeByValue: removeByValue,
    imageLoad: imageLoad,
    imageLoadList: imageLoadList,
    imageLoadAn: imageLoadAn,
    my_request: my_request,
    PageJump: PageJump,
    when_user_change_clear_the_storage: when_user_change_clear_the_storage,
    w_widths: w_widths,
    getConlantInfo: getConlantInfo,
    getConlantInfoSn: getConlantInfoSn,
    changeConsulant: changeConsulant,
    wholesale: wholesale,
    showContips: showContips,
    show_bar:show_bar,
    weixinPay: weixinPay,
}